package com.central.apps.handler.timeTask.contract;

import com.central.app.common.quartz.QuartzJob;
import com.central.app.common.util.DateUtils;
import com.central.app.service.HandlerService;
import com.central.apps.entity.BlMessage;
import com.central.apps.service.MessageService;
import com.central.bizcommon.model.schedule.JobParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
//禁止并发执行(Quartz不要并发地执行同一个job定义（这里指一个job类的多个实例）)
@DisallowConcurrentExecution
public class ConWarnTask extends QuartzJob {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private MessageService messageService;

    @Override
    public void executeJob(JobExecutionContext context, String jobnum, String jobname, List<JobParams> jobparams) {

        System.out.println("=================进入合同节点完成定时任务代码========================");
        //查询所有gq_connodenew表数据，未完成的，未终止，未关闭的合同节点
        String sql1 = "select id, connode,endtime,status from gq_connodenew where endtime<NOW() and status !='已完成' and endtime is not null and  concode in (select concode from gq_conaccount where constatus != '合同关闭' or constatus != '合同终止' or constatus != '合同验收' )";
        List<Map<String, Object>> list3 = handlerService.findBySql(sql1);
        if(CollectionUtils.isNotEmpty(list3)){
            for (Map<String, Object> stringObjectMap : list3) {
                Date endtime = (Date) stringObjectMap.get("endtime");
                int days = DateUtils.daysBetween(endtime,new Date());
                Map<String,Object> map = new HashMap<>();
                map.put("id",stringObjectMap.get("id"));
                map.put("postponedates",days);
                try {
                    handlerService.update("gq_connodenew",map);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        // 查询项目预警配置信息
        List<Map<String, Object>> cfgList = handlerService.findBySql("select * from gq_protaskwarn t where t.protaskwarnnum = '1005'");

        if (CollectionUtils.isEmpty(cfgList)) {
            return;
        }

        Map<String, Object> cfgMap = cfgList.get(0);
        Integer pwid = MapUtils.getInteger(cfgMap, "id");
        String calculateFormat = MapUtils.getString(cfgMap, "calculateformat");
        String tableName = MapUtils.getString(cfgMap, "tablename");
        String fieldName = MapUtils.getString(cfgMap, "fieldname");
        String nodeDesc = MapUtils.getString(cfgMap, "nodedesc");

        List<Map<String, Object>> cfgDtlList = handlerService.findBySql("select * from gq_protaskwarndtl t where t.ptwid = " + pwid);

        if (CollectionUtils.isEmpty(cfgDtlList)) {
            return;
        }

        // 获取当前日期
        Date date = new Date();
        String dateStr = "";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateStr = dateFormat.format(date);

        for (Map<String, Object> cfgDtlMap : cfgDtlList) {
            StringBuilder sql = new StringBuilder();
            sql.append("select * from ");
            sql.append(tableName);
            sql.append(" where ");

            String timeunitDesc = MapUtils.getString(cfgDtlMap, "timeunitdesc");
            String calculatefrom = MapUtils.getString(cfgDtlMap, "calculatefrom");
            String calculateto = MapUtils.getString(cfgDtlMap, "calculateto");
            Integer timeparamfrom = MapUtils.getInteger(cfgDtlMap, "timeparamfrom");
            Integer timeparamto = MapUtils.getInteger(cfgDtlMap, "timeparamto");
            String fieldname = MapUtils.getString(cfgDtlMap, "fieldname");
            String schedulestatus = MapUtils.getString(cfgDtlMap, "schedulestatus");
            String msgformat = MapUtils.getString(cfgDtlMap, "msgformat");

            // 时间单位分支处理
            switch (timeunitDesc) {
                case "天":
                    switch (calculateFormat) {
                        case "提前":
                            // 获取运算符号
                            String calculateSign = getCalculateSign(calculatefrom);
                            sql.append("date_add(");
                            sql.append(fieldName);
                            sql.append(" ,interval -");
                            sql.append(timeparamfrom);
                            sql.append(" day) ");
                            sql.append(calculateSign);
                            sql.append(" str_to_date('");
                            sql.append(dateStr);
                            sql.append("', '%Y-%m-%d')");

                            if (StringUtils.isNotEmpty(calculateto)) {
                                // 获取运算符号
                                String calculatetoSign = getCalculateSign(calculateto);
                                sql.append(" and date_add(");
                                sql.append(fieldName);
                                sql.append(" ,interval -");
                                sql.append(timeparamto);
                                sql.append(" day) ");
                                sql.append(calculatetoSign);
                                sql.append(" str_to_date('");
                                sql.append(dateStr);
                                sql.append("', '%Y-%m-%d')");
                            }
                            break;
                        case "滞后":
                            // 获取运算符号
                            String calculateSignFrom = getCalculateSign(calculatefrom);

                            sql.append(" str_to_date('");
                            sql.append(dateStr);
                            sql.append("', '%Y-%m-%d')");
                            sql.append(calculateSignFrom);
                            sql.append(" date_add(");
                            sql.append(fieldName);
                            sql.append(" ,interval ");
                            sql.append(timeparamfrom);
                            sql.append(" day) ");

                            if (StringUtils.isNotEmpty(calculateto)) {
                                // 获取运算符号
                                String calculateSignTo = getCalculateSign(calculateto);
                                sql.append(" and str_to_date('");
                                sql.append(dateStr);
                                sql.append("', '%Y-%m-%d')");
                                sql.append(calculateSignTo);
                                sql.append(" date_add(");
                                sql.append(fieldName);
                                sql.append(" ,interval ");
                                sql.append(timeparamto);
                                sql.append(" day) ");
                            }

                            break;
                        default:
                            break;
                    }
                    break;
                case "小时":
                    switch (calculateFormat) {
                        case "提前":
                            // 获取运算符号
                            String calculateSign = getCalculateSign(calculatefrom);
                            sql.append("date_add(");
                            sql.append(fieldName);
                            sql.append(" ,interval -");
                            sql.append(timeparamfrom);
                            sql.append(" hour) ");
                            sql.append(calculateSign);
                            sql.append(" str_to_date('");
                            sql.append(dateStr);
                            sql.append("', '%Y-%m-%d %H:%i:%S')");
                            break;
                        case "滞后":
                            // 获取运算符号
                            String calculateSignFrom = getCalculateSign(calculatefrom);
                            sql.append(" str_to_date('");
                            sql.append(dateStr);
                            sql.append("', '%Y-%m-%d %H:%i:%S')");
                            sql.append(calculateSignFrom);
                            sql.append(" date_add(");
                            sql.append(fieldName);
                            sql.append(" ,interval ");
                            sql.append(timeparamfrom);
                            sql.append(" hour) ");

                            if (StringUtils.isNotEmpty(calculateto)) {
                                // 获取运算符号
                                String calculateSignTo = getCalculateSign(calculateto);

                                sql.append(" and str_to_date('");
                                sql.append(dateStr);
                                sql.append("', '%Y-%m-%d %H:%i:%S')");
                                sql.append(calculateSignTo);
                                sql.append(" date_add(");
                                sql.append(fieldName);
                                sql.append(" ,interval ");
                                sql.append(timeparamto);
                                sql.append(" hour) ");

                            }

                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }

            List<Map<String, Object>> list = handlerService.findBySql(sql.toString());

            if (CollectionUtils.isNotEmpty(list)) {
                // 组织消息内容
                for (Map.Entry<String, Object> entry : cfgDtlMap.entrySet()) {
                    if (msgformat.contains("{" + entry.getKey() + "}")) {
                        msgformat = msgformat.replace("{" + entry.getKey() + "}", entry.getValue().toString());
                    }
                }

                for (Map<String, Object> map : list) {
                    Integer id = MapUtils.getInteger(map, "id");// id
                    Integer createuser = MapUtils.getInteger(map,"createuser");//创建人
                    String concode = MapUtils.getString(map,"concode");//合同编号
                    String nodecode = MapUtils.getString(map,"nodecode");//节点编号
                    Date endtime = (Date) map.get("endtime");//节点结束时间
                    int days = DateUtils.daysBetween(new Date(),endtime);
                    // 更新数据
                    if (StringUtils.isNotEmpty(fieldname) && StringUtils.isNotEmpty(schedulestatus)) {
                        handlerService.updateBySql("update " + tableName + " set " + fieldname + " = '" + schedulestatus + "' where id = " + id);
                    }
                    msgformat = "距离合同编号为"+concode+",合同节点编号为"+nodecode+"的节点结束时间还剩"+days+"天，请及时处理";
                    // 通知项目主管
                    BlMessage message = new BlMessage();
                    message.setTitle(nodeDesc);
                    message.setContent(msgformat);
                    message.setIsshow("未读");

                    // 查询项目主管人员信息

                    try {
                        //创建人
                        if (createuser != null) {
                            // 查询创建人员信息
                            String personinchargeId = "";
                            String personInChargeName = "";
                            List<Map<String, Object>> personList = handlerService.findBySql("select a.id, a.nickname from sys_user a inner join gq_person t on t.id = a.field10 where a.id = " + createuser);
                            if (CollectionUtils.isNotEmpty(personList)) {
                                Map<String, Object> personMap = personList.get(0);
                                personinchargeId = MapUtils.getString(personMap, "id");
                                personInChargeName = MapUtils.getString(personMap, "nickname");
                            }
                            // 通知合同节点创建人
                            message.setRecipient(personinchargeId);
                            message.setRecipientname(personInChargeName);
                            message.setCreateuser("1");
                            message.setCreateuserdesc("超级管理员");
                            Map<String, Object> map2 = new HashMap<>();
                            handlerService.addBizNum("messageApp","gq_message",map2);
                            String messagenum = MapUtils.getString(map2, "messagenum");
                            message.setMessagenum(messagenum);
                            message.setCreatetime(new Date());
                            message.setRecipientselect("接收人");
                            messageService.addMessage(message);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }

    }

    /**
     * 获得运算符号
     *
     * @param calculateWay
     * @return
     */
    private String getCalculateSign(String calculateWay) {
        String calculateSign = "=";
        switch (calculateWay) {
            case "大于":
                calculateSign = ">";
                break;
            case "小于":
                calculateSign = "<";
                break;
            case "大于等于":
                calculateSign = ">=";
                break;
            case "小于等于":
                calculateSign = "<=";
                break;
            default:
                break;
        }

        return calculateSign;
    }
}
